package com.virtualtrainer_01.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.virtualtrainer_01.model.Group;
import com.virtualtrainer_01.model.Model;
import com.virtualtrainer_01.model.Muscle;

public class MuscleDB extends SQLiteDB {
	public MuscleDB(Context c) {
		super(c, DATABASE_TABLE);
	}

	public static final String KEY_ID = "_id";
	public static final String KEY_NAME = "name";
	public static final String KEY_ID_GROUP = "id_group";
	public static final String KEY_DESCRIPTION = "description";
	public static final String DATABASE_TABLE = "muscle";

	public long createEntry(Model entry) {
		Muscle m = (Muscle) entry;
		GroupDB gdb = new GroupDB(ourContext);
		ContentValues cv = new ContentValues();
		cv.put(KEY_NAME, m.getName());
		cv.put(KEY_DESCRIPTION, m.getDescription());
		gdb.open();
		cv.put(KEY_ID_GROUP, gdb.getId(m.getGroup()));
		gdb.close();
		return ourDatabase.insert(DATABASE_TABLE, null, cv);
	}

	public String getData() {
		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_ID_GROUP };
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
				null, null);
		String result = "";

		int iRow = c.getColumnIndex(KEY_ID);
		int iName = c.getColumnIndex(KEY_NAME);
		int iDescription = c.getColumnIndex(KEY_DESCRIPTION);
		int iIdGroup = c.getColumnIndex(KEY_ID_GROUP);

		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
			result = result + c.getString(iRow) + " " + c.getString(iName)
					+ " " + c.getString(iDescription) + " "
					+ c.getString(iIdGroup) + "\n";
		return result;
	}
	
	public Muscle getMuscle(int id) {
		String sql = "SELECT * FROM " + DATABASE_TABLE + " t where t." + KEY_ID
				+ "=" + "'" + id + "';";
		Cursor c = ourDatabase.rawQuery(sql, null);

		int iName = c.getColumnIndex(KEY_NAME);
		int idGroup = c.getColumnIndex(KEY_ID_GROUP);
		int iDescription = c.getColumnIndex(KEY_DESCRIPTION);

		Muscle m = new Muscle();
		GroupDB gdb = new GroupDB(ourContext);
		gdb.open();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			m.setName(c.getString(iName));
			m.setDescription(c.getString(iDescription));			
			Group g = gdb.getGroup(Integer.parseInt(c.getString(idGroup)));			
			m.setGroup(g);
		}
		gdb.close();
		return m;
	}
}
